package org.yelongframework.pdf.impl.pdfbox;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.yelongframework.pdf.PdfTools;

/**
 * apache pdfbox 实现 PDF工具
 * 
 * @since 1.0.0
 */
public class PDFBoxPDFTools implements PdfTools {

	/** 默PDF页转换为图片的格式为jpg */
	public static final String DEFAULT_PAGE_TO_IMAGE_TYPE = "jpg";

	/** 默PDF页转换为图片的格式 */
	private String defaultPageToImageType = DEFAULT_PAGE_TO_IMAGE_TYPE;

	@Override
	public List<byte[]> splitPageToImagesBytes(InputStream inputStream) throws IOException {
		return splitPageToImagesBytes(inputStream, defaultPageToImageType);
	}

	@Override
	public List<byte[]> splitPageToImagesBytes(InputStream inputStream, String imageType) throws IOException {
		List<OutputStream> imagesOutputStreams = splitPageToImagesOutputStream(inputStream, imageType,
				x -> new ByteArrayOutputStream());
		List<byte[]> imagesBytes = new ArrayList<>(imagesOutputStreams.size());
		for (OutputStream outputStream : imagesOutputStreams) {
			imagesBytes.add(((ByteArrayOutputStream) outputStream).toByteArray());
		}
		return imagesBytes;
	}

	@Override
	public List<OutputStream> splitPageToImagesOutputStream(InputStream inputStream,
			ImageOutputStreamSupplier imageOutputStreamFunction) throws IOException {
		return splitPageToImagesOutputStream(inputStream, defaultPageToImageType, imageOutputStreamFunction);
	}

	@Override
	public List<OutputStream> splitPageToImagesOutputStream(InputStream inputStream, String imageType,
			ImageOutputStreamSupplier imageOutputStreamFunction) throws IOException {
		PDDocument document = PDDocument.load(inputStream);
		PDFRenderer renderer = new PDFRenderer(document);
		// PDF页数
		int pageCount = document.getNumberOfPages();
		if (pageCount < 0) {
			return Collections.emptyList();
		}
		List<OutputStream> imagesBytes = new ArrayList<>(pageCount);
		for (int i = 0; i < pageCount; i++) {
			BufferedImage image = renderer.renderImageWithDPI(i, 144);
			OutputStream outputStream = imageOutputStreamFunction.get(i);
			ImageIO.write(image, imageType, outputStream);
			imagesBytes.add(outputStream);
		}
		return imagesBytes;
	}

	public String getDefaultPageToImageType() {
		return defaultPageToImageType;
	}

	public void setDefaultPageToImageType(String defaultPageToImageType) {
		this.defaultPageToImageType = defaultPageToImageType;
	}

}
